package md.mru.core.service;

import md.mru.core.common.BaseDtoMapper;
import md.mru.core.domains.administration.User;
import md.mru.core.dtos.UserDto;
import md.mru.core.repositories.UserRepository;
import md.mru.frontend.utils.AppUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author sergiu.marin
 * @since 29.04.2014
 */
@Service
public class LoginService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    @Qualifier(value = "dtoMapper")
    private BaseDtoMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.loadUserByUsername(email);

        if (user == null) {
            throw new UsernameNotFoundException("Username sau parola gresita.");
        }

        return new AppUserDetails(mapper.map(user, UserDto.class));
    }
}
